<template>
  <MesBox title="选择储位" v-model="dialogVisible">
    <MesForm
      ref="myForm"
      :formFields="formFields"
      :formRules="formRules"
    ></MesForm>
    <template #footer>
      <el-button type="danger" @click="save">
        <i class="el-icon-check"></i>
        保存
      </el-button>
    </template>
  </MesBox>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue'
import MesForm from '@/components/basic/MesForm'
import MesBox from '@/components/basic/MesBox'

defineEmits(['parentCall'])
const that = getCurrentInstance().appContext.config.globalProperties
let dialogVisible = ref(false)
const myForm = ref(null)
let formFields = ref({
  PostID: '',
})
let selects = ref([])
let search = null

let formRules = [
  [
    {
      title: '储位',
      field: 'PostID',
      type: 'select',
      dataKey: 'BCPStorageLocation',
      required: true,
    },
  ],
]

const open = (type, data, searchFun) => {
  formRules[0][0].dataKey =
    type == 'BCP' ? 'BCPStorageLocation' : 'CPStorageLocation'
  selects.value = data
  search = searchFun
  dialogVisible.value = true
}

const save = () => {
  myForm.value.validate(async (valid) => {
    if (valid) {
      selects.value = selects.value.map((item) => {
        return {
          ...item,
          PostID: formFields.value.PostID,
        }
      })

      let url = ''
      let params = {}
      if (formRules[0][0].dataKey == 'BCPStorageLocation') {
        url = '/api/Ware_SPWarehouse/InsertWarehouseAdd'
        params = {
          addSPWarehouse: selects.value,
        }
      } else {
        // let arr = []
        // selects.value.forEach((item) => {
        //   let index = arr.findIndex((i) => i.ProductCode == item.ProductCode)
        //   if (index !== -1) {
        //     arr[index].Qnty += item.Qnty
        //   } else {
        //     arr.push(item)
        //   }
        // })
        url = '/api/Ware_FSProduct/InsertFSProduct'
        params = {
          list: selects.value,
        }
      }

      let res = await that.http.post(url, params, true)
      if (res.status) {
        that.$message.success(res.message)
        search()
      } else {
        if (res.message === '') {
          that.$message.error('审核失败')
        } else {
          that.$message.error(res.message)
        }
      }
      formFields.value.PostID = ''
      dialogVisible.value = false
    }
  })
}

defineExpose({ open })
</script>

<style lang="less" scoped></style>
